﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Taoyl.CodeTraceBLL;
using Taoyl.CodeTraceHelper;
using Taoyl.CodeTraceModels;
using xbd.DataConvertLib;

namespace Taoyl.CodeTracePro
{
    public partial class FrmRecord : Form
    {
        public FrmRecord()
        {
            InitializeComponent();

            this.dtp_Start.Value=Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            this.dtp_End.Value = DateTime.Now;

            this.cmb_Result.Items.AddRange(new string[] { "ALL", "OK", "NG" });
            this.cmb_Result.SelectedIndex = 0;

            this.dgv_Record.AutoGenerateColumns = false;
            this.dgv_Record.Columns[1].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
        }

        //创建业务层对象
        private CodeRecordManager recordManager=new CodeRecordManager();

        //查询的结果
        private List<CodeRecord> codeRecords = new List<CodeRecord>();

        private void QueryProcess(DateTime start,DateTime end)
        {
            string result=this.cmb_Result.Text=="ALL"?string.Empty:this.cmb_Result.Text;
            String code = this.txt_Code.Text.Trim();
            bool order = this.cmb_Order.SelectedIndex == 0;

            if (start>end)
            {
                new FrmMsgNoAck("开始时间不能大于结束时间", "查询异常").ShowDialog();
                return;
                
            }

            Task<OperateResult<List<CodeRecord>>> task = Task.Run(() =>
            {
                return recordManager.QueryCodeRecords(start,end,code,result,order);
            });

            task.ContinueWith(Task =>
            {
                if (task.Result.IsSuccess)
                {
                   

                    if (task.Result.Content.Count>0)
                    {
                        //存到成员变量中，便于后续导出打印
                        this.codeRecords = task.Result.Content;
                        this.Invoke(new Action(() =>
                        {
                            //更新界面
                            this.dgv_Record.DataSource = null;
                            this.dgv_Record.DataSource = this.codeRecords;
                        }));
                    }
                    else
                    {

                        this.Invoke(new Action(() =>
                        {
                            new FrmMsgNoAck("查询结果为空,请检查!" , "查询为空").ShowDialog();
                        }));
                    }

                }
                else
                {
                    this.Invoke(new Action(() =>
                    {
                        new FrmMsgNoAck("查询失败:" + task.Result.Message, "查询失败").ShowDialog();
                    } ) );
                }
            });
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            DateTime start = this.dtp_Start.Value;
            DateTime end = this.dtp_End.Value;
            QueryProcess(start,end  );
        }

        private void btn_LastHour_Click(object sender, EventArgs e)
        {
            DateTime start = DateTime.Now.AddHours(-1.0f);
            DateTime end = DateTime.Now;
            QueryProcess(start, end);
        }

        private void btn_LastDay_Click(object sender, EventArgs e)
        {
            DateTime start = DateTime.Now.AddDays(-1.0f);
            DateTime end = DateTime.Now;
            QueryProcess(start, end);
        }

        private void btn_Export_Click(object sender, EventArgs e)
        {
            if (this.codeRecords==null||this.codeRecords.Count==0)
            {
                new FrmMsgNoAck("请先查询到结果，再执行导出!", "数据导出").ShowDialog();
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title="请选择导出文件";
            sfd.Filter = "Excel文件(*.xlsx)|*.xlsx|CSV文件(*.csv)|*.csv";
            sfd.FilterIndex = 1;
            sfd.RestoreDirectory = true;
            sfd.FileName = "生产记录_" + DateTime.Now.ToString("yyyyMMdd_HHmmss");

            if (sfd.ShowDialog()==DialogResult.OK)
            {
                try
                {
                    MiniExcelLibs.MiniExcel.SaveAs(sfd.FileName, this.codeRecords, overwriteFile: true);
                    Process.Start(sfd.FileName);
                }
                catch (Exception ex)
                {
                    new FrmMsgNoAck("导出异常"+ex.Message, "数据导出").ShowDialog();
                }
            }
        }

        /// <summary>
        /// DGV行号绘制事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Record_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint(this.dgv_Record, e);
        }

        private void btn_Print_Click(object sender, EventArgs e)
        {
            PrintHelper.Print_DataGridView(this.dgv_Record, true);
        }
    }
}
